class Banner {
  constructor(select) {
    this.ele = document.querySelector(select)
    this.imgBox = this.ele.querySelector('.t1')
    this.pointBox = this.ele.querySelector('.pointBox')
    this.index = 0

    this.timerId = 0

    this.init()
  }
  init() {

    this.setPoint()

    this.autoPlay()

    this.overOut()

    this.bindEvent()
  }


  setPoint() {

    const pointNum = this.imgBox.children.length
    const frg = document.createDocumentFragment()

    for (let i = 0; i < pointNum; i++) {
      const li = document.createElement('li')
      li.classList.add('point')
      if (i === 0) li.classList.add('active')
      li.dataset.i = i
      frg.appendChild(li)
    }
    this.pointBox.appendChild(frg)
    this.pointBox.style.width = pointNum * (20 + 10) + 'px'
  }

  changeOne(type) {

    this.imgBox.children[this.index].classList.remove('active')
    // 操作焦点
    this.pointBox.children[this.index].classList.remove('active')

    // 2. 通过 type 来判断, 决定 this.index 的值
    switch (type) {
      case true:
        // 下一张
        this.index++
        break
      case false:
        // 上一张
        this.index--
        break
      default:
        // 某一张
        this.index = type
    }

    // 3. 调整一下 this.index 的边界值
    if (this.index < 0) this.index = this.imgBox.children.length - 1
    if (this.index >= this.imgBox.children.length) this.index = 0


    this.imgBox.children[this.index].classList.add('active')
    this.pointBox.children[this.index].classList.add('active')
  }


  autoPlay() {

    this.timerId = setInterval(() => {

      this.changeOne(true)
    }, 2000)
  }

  overOut() {
    this.ele.addEventListener('mouseover', () => clearInterval(this.timerId))
    this.ele.addEventListener('mouseout', () => this.autoPlay())
  }


  bindEvent() {

    this.ele.addEventListener('click', e => {

      e = e || window.event

      const target = e.target || e.srcElement
      if (target.className === 'point') {

        const i = target.dataset.i - 0

        this.changeOne(i)
      }
    })
  }
}
